package cn.didi.feidi.androidorder.adapter;

import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;

import java.util.ArrayList;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.assembly.DeleteGoodsFragmentDialog;
import cn.didi.feidi.androidorder.databinding.ItemMainShoppingCarBinding;
import cn.didi.feidi.androidorder.fragment.FeiDiMainBaseFragment;
import cn.didi.feidi.androidorder.model.ShoppingCar;

/**
 * Created by jinxiong on 2017/8/22.
 */

public class MainShoppingCarRecyclerViewAdapter extends
        RecyclerView.Adapter<MainShoppingCarRecyclerViewAdapter.ViewHolder> {

    final boolean DEBUG = false;
    FeiDiMainBaseFragment mBaseFragment;
    ArrayList<ShoppingCar> shoppingCars;
    SelectCallBack callback;
    ArrayList<ShoppingCar> selectedGoods;
    private AsyncSession asyncSession;


    public MainShoppingCarRecyclerViewAdapter(FeiDiMainBaseFragment feiDiMainBaseFragment) {

        mBaseFragment = feiDiMainBaseFragment;
        shoppingCars = new ArrayList<>();
        selectedGoods = new ArrayList<>();
        asyncSession = OrderApplication.getDaoSession().startAsyncSession();

    }

    public void setCallback(SelectCallBack callback) {
        this.callback = callback;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        ItemMainShoppingCarBinding binding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.getContext()), R.layout.item_main_shopping_car, parent, false);

        ViewHolder viewHolder = new ViewHolder(binding.getRoot());
        viewHolder.setBinding(binding);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {


        initView(holder, position);
        addListener(holder, position);
        if (shoppingCars.size() > 0) {
            holder.getBinding().setShoppingCar(shoppingCars.get(position));

            Glide.with(mBaseFragment)
                    .load(shoppingCars.get(position).getPicUrl())
                    .placeholder(R.drawable.logo)
                    .into(holder.getBinding().mainShoppingCarRecyclerViewItemWaterPhotoIv);
        }


    }

    private void initView(ViewHolder holder, int position) {

        int size = selectedGoods.size();

        ItemMainShoppingCarBinding binding = holder.binding;
        binding.mainShoppingCarRecyclerViewItemSelectIv.setSelected(false);

        Object obj = shoppingCars.get(position);
        for (int i = 0; i < size; i++) {

            if (obj.equals(selectedGoods.get(i))) {
                binding.mainShoppingCarRecyclerViewItemSelectIv.setSelected(true);
                break;
            }
        }

    }

    private void addListener(ViewHolder holder, final int position) {

        final ItemMainShoppingCarBinding binding = holder.binding;
        binding.getRoot().setLongClickable(true);
        binding.getRoot().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                final DeleteGoodsFragmentDialog deleteGoodsFragmentDialog = new DeleteGoodsFragmentDialog();
                deleteGoodsFragmentDialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        asyncSession.setListenerMainThread(new AsyncOperationListener() {
                            @Override
                            public void onAsyncOperationCompleted(AsyncOperation operation) {

                                if (operation.isFailed()) {
                                    return;
                                }

                                Object object = shoppingCars.remove(position);
                                for (int i = 0; i < selectedGoods.size(); i++) {

                                    if (selectedGoods.get(i).equals(object)) {

                                        selectedGoods.remove(object);
                                        if (callback != null) {
                                            callback.callback(selectedGoods);
                                        }
                                        break;
                                    }

                                }

                                notifyDataSetChanged();

                            }
                        });

                        asyncSession.delete(shoppingCars.get(position));
                        deleteGoodsFragmentDialog.dismiss();


                    }
                });
                deleteGoodsFragmentDialog.show(mBaseFragment.getChildFragmentManager(), "delete");

                return true;
            }
        });


        binding.mainShoppingCarRecyclerViewItemDownIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int count = Integer.parseInt(binding.mainShoppingCarRecyclerViewItemCountTv.getText().toString());
                count--;
                count = count <= 0 ? 1 : count;

                ShoppingCar shoppingCar = shoppingCars.get(position);
                shoppingCar.setBuyCount(count);
                updateShoppingCar(shoppingCar, binding);

            }
        });


        binding.mainShoppingCarRecyclerViewItemUpIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                int count = Integer.parseInt(binding.mainShoppingCarRecyclerViewItemCountTv.getText().toString());
                count++;

                count = count >= 99 ? 99 : count;


                ShoppingCar shoppingCar = shoppingCars.get(position);
                shoppingCar.setBuyCount(count);
                updateShoppingCar(shoppingCar, binding);

            }
        });

        binding.mainShoppingCarRecyclerViewItemSelectIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (v.isSelected()) {
                    v.setSelected(false);
                    selectedGoods.remove(shoppingCars.get(position));
                } else {
                    v.setSelected(true);
                    selectedGoods.add(shoppingCars.get(position));
                }

                if (callback != null) {
                    callback.callback(selectedGoods);
                }


            }
        });
    }

    private void updateShoppingCar(final ShoppingCar shoppingCar, final ItemMainShoppingCarBinding binding) {
        asyncSession.setListenerMainThread(new AsyncOperationListener() {
            @Override
            public void onAsyncOperationCompleted(AsyncOperation operation) {

                if (operation.isFailed()) {
                    return;
                }

                ShoppingCar shoppingCar1 = (ShoppingCar) operation.getParameter();
                binding.mainShoppingCarRecyclerViewItemCountTv.setText(String.valueOf(shoppingCar1.getBuyCount()));


                int size = selectedGoods.size();

                for (int i = 0; i < size; i++) {

                    ShoppingCar tem = selectedGoods.get(i);
                    if (tem.getBucketTypeId().equals(shoppingCar1.getBucketTypeId())) {
                        tem.setBuyCount(shoppingCar1.getBuyCount());
                        break;
                    }

                }


                if (callback != null) {
                    callback.callback(selectedGoods);
                }


            }
        });
        asyncSession.update(shoppingCar);
    }

    @Override
    public int getItemCount() {
        return shoppingCars.size();
    }

    public int getSelectedGoodsSize() {
        return selectedGoods.size();
    }

    public ArrayList<ShoppingCar> getSelectedGoods() {
        return selectedGoods;
    }

    /**
     * @param selectAll true 为选择全部 ，false 为清除全部
     */
    public void setSelectedGoods(boolean selectAll) {
        selectedGoods.clear();
        if (selectAll) {
            selectedGoods.addAll(shoppingCars);
        }
        notifyDataSetChanged();
    }

    public void setShoppingCars(ArrayList<ShoppingCar> shoppingCars) {

        this.shoppingCars.clear();

        if (shoppingCars != null) {
            this.shoppingCars.addAll(shoppingCars);
        }
        notifyDataSetChanged();
    }

    public float getSelectedPrice() {

        float price = 0;
        if (selectedGoods.size() == 0) {
            return price;
        }

        int size = selectedGoods.size();

        for (int i = 0; i < size; i++) {

            ShoppingCar shoppingCar = selectedGoods.get(i);
            price += (shoppingCar.getBuyCount() * shoppingCar.getPrForWaUs());

        }

        return price;


    }

    public void clearSelectedShoppingCar() {
        selectedGoods.clear();
        notifyDataSetChanged();
    }

    public void clearSelectedFromShoppingCars(ArrayList<ShoppingCar> shoppingCars) {

        if (shoppingCars != null) {
            this.shoppingCars.removeAll(shoppingCars);
            notifyDataSetChanged();
        }
    }

    public void deleteSelectedFromShoppingCars(ArrayList<ShoppingCar> shoppingCars) {

        if (shoppingCars != null) {
            this.shoppingCars.removeAll(shoppingCars);
            notifyDataSetChanged();
        }
        for (ShoppingCar shop : shoppingCars) {
            asyncSession.delete(shop);
        }

    }


    public interface SelectCallBack {
        void callback(ArrayList<ShoppingCar> objects);
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private ItemMainShoppingCarBinding binding;

        public ViewHolder(View itemView) {
            super(itemView);
        }

        public ItemMainShoppingCarBinding getBinding() {
            return binding;
        }

        public void setBinding(ItemMainShoppingCarBinding binding) {
            this.binding = binding;
        }
    }
}
